//
//  BHScrollView.m
//  轮播图
//
//  Created by dllo on 16/1/14.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "NHScrollView.h"

#import "UIImageView+WebCache.h"

#define Width (self.frame.size.width)
#define Height (self.frame.size.height)

#pragma mark 协议方法,暂无


@interface NHScrollView ()<UIScrollViewDelegate>
{
    NSInteger imagesCount;
}
// 图片数据源
@property(nonatomic, retain)NSArray *imagesData;
// 保存当前轮播图的类型
@property(nonatomic, assign)NHScrollViewStyle scrollViewStyle;
// 控制器
@property(nonatomic, retain)NSTimer *timer;

@end
@implementation NHScrollView

#pragma mark 初始化方法
// 重写初始化方法
- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    
    if(self){
        // 签协议,指定代理人
        self.delegate = self;
        // 设置数据源
        self.imagesData = [self.dataSource bringImageDataNHScrollView:self];
        // 创建普通视图
        [self createNoneView];
    }
    return self;
}
- (id)initWithFrame:(CGRect)frame NHScrollViewStyle:(NHScrollViewStyle)scrollViewStyle{
    self = [super initWithFrame:frame];
    if(self){
        // 签协议,指定代理人
        self.delegate = self;
        
        // 根据不同的轮播图的类型,调用不同的创建视图的方法
        if(scrollViewStyle == NHScrollViewStyleNone){
            [self createNoneView];
        }
        else if(scrollViewStyle == NHScrollViewStyleNormal){
            [self createNomalView];
        }
        else if(scrollViewStyle == NHScrollViewStyleInfiniteLoop){
            [self createInfiniteLoop];
        }
        else if (scrollViewStyle == NHScrollViewStyleAutomaticInfiniteLoop){
            [self createAutomaticInfiniteLoop];
        }
        // 保存当前轮播图的类型
        self.scrollViewStyle = scrollViewStyle;
        
    }
    return self;
}


#pragma mark 创建无视图
- (void)createNoneView{
    // 获得数据源的个数
    imagesCount = self.imagesData.count;
    // 设置轮播图滚动的界面的大小
    self.contentSize = CGSizeMake(Width * imagesCount, Height);
    
    // 创建ImageView
    for(NSInteger i = 0; i < imagesCount; i++){
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(i * Width, 0, Width, Height)];
        
        [imageView sd_setImageWithURL:[NSURL URLWithString:self.imagesData[i]] placeholderImage:[UIImage imageNamed:@"noPic_128_01"]];
        [self addSubview:imageView];
        
        // 添加点击手势
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickScrollView)];
        imageView.userInteractionEnabled = YES;
        [imageView addGestureRecognizer:tap];
    }
}
#pragma mark 创建普通视图
- (void)createNomalView{
    // 创建无视图
    [self createNoneView];
    
    // 添加额外的功能和属性
    
    // 设置按页显示
    self.pagingEnabled = YES;
    // 设置边界不可回弹
    self.bounces = NO;
    // 设置滚动条不可见
    self.showsHorizontalScrollIndicator = NO;
    self.showsVerticalScrollIndicator = NO;
}

#pragma mark 创建无限循环视图
- (void)createInfiniteLoop{
    
    // 当图片的数据不为空的时候才会创建
    if(self.imagesData.count != 0){
        // 获得数据源的个数
        imagesCount = self.imagesData.count;
        // 设置轮播图滚动的界面的大小
        self.contentSize = CGSizeMake(Width * (imagesCount + 2), Height);
        // 设置按页显示
        self.pagingEnabled = YES;
        // 设置边界不可回弹
        self.bounces = NO;
        // 设置滚动条不可见
        self.showsHorizontalScrollIndicator = NO;
        self.showsVerticalScrollIndicator = NO;
        // 设置偏移量
        self.contentOffset = CGPointMake(Width, 0);
        
        // 创建ImageView
        for(NSInteger i = 1; i < imagesCount + 1; i++){
            // 创建
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(i * Width, 0, Width, Height)];
            // 添加图片
            [imageView sd_setImageWithURL:[NSURL URLWithString:self.imagesData[i - 1]] placeholderImage:[UIImage imageNamed:@"noPic_128_01"]];
            // 将ImageView添加到当前的NHScrollView上
            [self addSubview:imageView];
            
            // 添加点击手势
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickScrollView)];
            imageView.userInteractionEnabled = YES;
            [imageView addGestureRecognizer:tap];
        }
        
        // 添加第一个ImageView
        UIImageView *firstImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, Width, Height)];
        [firstImage sd_setImageWithURL:[NSURL URLWithString:self.imagesData[imagesCount - 1]] placeholderImage:[UIImage imageNamed:@"noPic_128_01"]];
        [self addSubview:firstImage];
        // 添加点击手势
        UITapGestureRecognizer *tapFirst = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickScrollView)];
        firstImage.userInteractionEnabled = YES;
        [firstImage addGestureRecognizer:tapFirst];
        
        // 添加最后一个
        UIImageView *lastImage = [[UIImageView alloc] initWithFrame:CGRectMake((imagesCount + 1) * Width, 0, Width, Height)];
        [lastImage sd_setImageWithURL:[NSURL URLWithString:self.imagesData[0]] placeholderImage:[UIImage imageNamed:@"noPic_128_01"]];
        [self addSubview:lastImage];
        
        // 添加点击手势
        UITapGestureRecognizer *tapLast = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickScrollView)];
        lastImage.userInteractionEnabled = YES;
        [lastImage addGestureRecognizer:tapLast];
    }
}
#pragma mark 创建自动,无限循环视图
- (void)createAutomaticInfiniteLoop{
    
    // 创建无限循环轮播图
    [self createInfiniteLoop];

    // 添加自动跳转功能
    // 延时3秒后执行,创建一个新的计时器
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(ScrollAfterTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if(self.timer == nil){
            self.timer = [NSTimer scheduledTimerWithTimeInterval:TimeInterval target:self selector:@selector(scrollViewAutomaticInfiniteLoop) userInfo:nil repeats:YES];
            
            [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
            self.timer.fireDate = [NSDate distantPast];
        }
    });
}
#pragma mark 实现自动跳转的功能
- (void)scrollViewAutomaticInfiniteLoop{
    NSInteger x = self.contentOffset.x / Width;
    NSLog(@"%ld",x);
    if(x == imagesCount){
        x = 0;
        self.contentOffset = CGPointMake(0, 0);
    }
    [UIView animateWithDuration:0.5 animations:^{
        self.contentOffset = CGPointMake((x + 1) * Width, 0);
    }];
}
#pragma mark 开始和暂停轮播图
// 暂停轮播图
- (void)pause{
    self.timer.fireDate = [NSDate distantPast];
}

// 开始轮播图
- (void)action{
    self.timer.fireDate = [NSDate distantFuture];
}

#pragma mark 刷新数据
- (void)reloadData{
    self.imagesData = [self.dataSource bringImageDataNHScrollView:self];
    // 将当前的ScrollView的子视图清空
    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    // 为ScrollView重新赋值
    // 根据不同的轮播图的类型,调用不同的创建视图的方法
    
    if(self.scrollViewStyle == NHScrollViewStyleNone){
        // 无视图
        [self createNoneView];
    }
    else if(self.scrollViewStyle == NHScrollViewStyleNormal){
        // 普通视图
        [self createNomalView];
    }
    else if(self.scrollViewStyle == NHScrollViewStyleInfiniteLoop){
        // 无限循环轮播图
        [self createInfiniteLoop];
    }
    else if (self.scrollViewStyle == NHScrollViewStyleAutomaticInfiniteLoop){
        // 自动,无限循环的轮播图
        [self createAutomaticInfiniteLoop];
    }
}
#pragma mark 实现轮播图的点击方法
- (void)clickScrollView{
    
    NSInteger index = (NSInteger)self.contentOffset.x / Width;
    
    [self.dataSource scrollView:self didSeclectRowAtIndexPath:index];
}

#pragma mark 实现UIScrollView的协议方法,实现无限循环
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if(scrollView.contentOffset.x == (imagesCount + 1) * Width){
        self.contentOffset = CGPointMake(Width, 0);
    }
    else if(scrollView.contentOffset.x == 0){
        self.contentOffset = CGPointMake(imagesCount * Width, 0);
    }
}


@end
